home *** CD-ROM | disk | FTP | other *** search
- Path: dawn.mmm.com!news
- From: kjhopps@mmm.com (Kevin J Hopps)
- Newsgroups: comp.lang.c++
- Subject: Re: aborting a constructor
- Date: 8 Feb 1996 14:50:37 GMT
- Organization: 3M - St. Paul, MN 55144-1000 US
- Message-ID: <4fd2jt$hf3@dawn.mmm.com>
- References: <310DA3AB.6E32@tribeca.ios.com> <4f8eo6$kik@druid.borland.com>
- Reply-To: kjhopps@mmm.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Pete Becker (pete@borland.com) wrote:
- > In article <310DA3AB.6E32@tribeca.ios.com>, leonardj@tribeca.ios.com says...
- > >
- > >In an earlier post, I asked how you use 'new' and a constructor in order to
- > deal with the
- > >following situation:
- > > You have a class, let's call it WindowClass, which, when it is
- > instantiated, does the
- > >following:
- > > 1: It opens the file "filename", and gets its size.
- > > 2: It allocates memory to hold "filename".
- > > 3: It loads "filename" into that memory.
- > > 4: It opens a window to display "filename".
- > > Now let's suppose that after it performs steps 1 thru 3 it cannot open
- > the window, what does it
- > >do? Furthermore, how do you code for this kind of situation in C++ in
- > general? My first thought was
- > >that the constructor should de-allocate all of the resources that it had
- > received so far. Then it
- > >should throw an exception. The question that I had was: what's going to
- > happen to the memory that
- > >was allocated for the object's data members?
-
- > The compiler is responsible for generating code that will release allocated
- > memory when a constructor throws an exception.
-
- > >I nother words: what happens to an object if its
- > >constructor aborts?
-
- > This is an entirely different question, and its answer depends on what you
- > mean by "aborts".
-
- If by "abort" you mean "throws an exception," then the following will happen:
- 1) Any fully constructed sub-objects will be destroyed, and
- 2) If the object was allocated in a new-expression, the storage for the
- object will be deleted also (if placement-new was not used).
-
- So in your example above, if step 4 fails, the memory allocated for the object
- itself will be released, but the memory allocated in step 2 will not be
- released unless the destructor of a fully constructed sub-object releases it.
- The same is true for the file opened in step 1 -- it will not be closed
- automatically.
- --
- Kevin J. Hopps e-mail: kjhopps@mmm.com
- 3M Company phone: (612) 737-4643
- 3M Center, Bldg. 235-2D-57 fax: (612) 737-2700
- St. Paul, MN 55144-1000 Opinions are my own. I don't speak for 3M.
- But 3M speaks for me -- I did not write the following line:
-
- Opinions expressed herein are my own and may not represent those of 3M.
-